package com.cacode.androidShell;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.*;
import android.widget.Toast;

import java.util.Date;

/**
 * APP入口
 *
 * @Author cacode
 */
public class MainActivity extends Activity {
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;
    private ValueCallback<Uri> uploadMessage;
    // 点击返回要退出的次数
    private int backCount = 0;
    // 第一次返回的时间
    private Date firstBackDate;
    // 3000毫秒内返回两次就退出系统
    private int exitSecond = 3000;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 设置标题栏颜色
        Window window = this.getWindow();
        window.setStatusBarColor(Color.parseColor(this.getString(R.string.color)));
        // 设置容器
        setContentView(R.layout.activity_main);
        // 浏览器设置
        WebView wv = findViewById(R.id.webView);
        WebSettings ws = wv.getSettings();
        ws.setSupportZoom(true);
        ws.setUseWideViewPort(true);
        ws.setLoadWithOverviewMode(true);
        ws.setDefaultTextEncodingName("utf-8");
        ws.setBuiltInZoomControls(false);
        ws.setDomStorageEnabled(true);
        ws.setGeolocationEnabled(true);
        ws.setJavaScriptEnabled(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        wv.loadUrl(Strings.wholeDomain);
        wv.requestFocus();
        wv.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {
                super.onReceivedIcon(view, icon);
            }

            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }

            /**
             * 使用js的alert弹出时
             * @param view
             * @param url
             * @param message
             * @param result
             * @return
             */
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("弹出框");
                builder.setMessage(message);
                builder.setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm());
                builder.setNegativeButton(android.R.string.cancel, (dialog, which) -> result.cancel());
                builder.setCancelable(false);
                builder.create();
                builder.show();

                return true;
            }

            // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url,
                                       String message, final JsResult result) {
                return true;
            }

            // 处理定位权限请求
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        });
        //点击超链接的时候重新在原来的进程上加载URL
        wv.setWebViewClient(new WebViewClient() {
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在6.0才出现
                int statusCode = errorResponse.getStatusCode();
                System.out.println("onReceivedHttpError code = " + statusCode);
                if (404 == statusCode || 500 == statusCode) {
                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                    view.loadUrl("file:///android_asset/404.html");
                }
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.contains(Strings.domain)) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(url);
                    intent.setData(content_url);
                    startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                CookieSyncManager.getInstance().sync(); //同步cookie
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        // 下载
        wv.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
            url = url.replace("blob:", "");
            Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
            //处理下载事件
//                WebviewUtil.downloadBySystem(url, contentDisposition, mimetype, MainActivity.this);
            WebviewUtil.openBrowser(MainActivity.this, url);
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                Uri uri = Uri.parse(url);
//                intent.addCategory(Intent.CATEGORY_BROWSABLE);
//                intent.setData(uri);
//                startActivity(intent);
        });


        wv.addJavascriptInterface(new JavaMethods(wv, this), "java");
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location loc) {
                Log.i("a", "onLocationChanged. loc: " + loc);
                if (loc != null) {
                    Log.i("a", "onLocationChanged. latitude: " + loc.getLatitude() + " , longtitude: " + loc.getLongitude());
                }
            }
        };
    }

    /**
     * 手机返回按钮触发时 返回上一个页面
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            WebView wv = findViewById(R.id.webView);
            // 如果可以返回上一个页面就返回
            if (wv.canGoBack()) {
                wv.goBack();
            } else {
                // 事件次数加一用于线程控制退出
                this.backCount++;
                if (this.backCount == 1) {
                    // 时间统计
                    firstBackDate = new Date();
                }
                Toast.makeText(this, "再次返回将退出系统", Toast.LENGTH_SHORT).show();
                // 返回两次才退出
                new Thread(() -> {
                    while (true) {
                        if (backCount > 1) {
                            System.exit(0);
                        } else {
                            // 如果时间跟第一次退出的时间大于设置的退出范围时间,就还原
                            if (new Date().getTime() - this.firstBackDate.getTime() > this.exitSecond) {
                                this.backCount = 0;
                                this.firstBackDate = null;
                                break;
                            }
                        }
                    }
                }).start();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
}
